﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Swashbuckle.AspNetCore.Annotations;
using System;
using System.Threading.Tasks;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.Filters;
using VisionCloud.Service.Fms;
using VisionCloud.Service.Ms;

namespace VisionCloud.Api.Controllers.Inner
{
    [SystemModule("定时器相关接口")]
    [ApiVersion("1.0")]
    [Route("api/inner/[controller]/[Action]")]
    [ApiExplorerSettings(GroupName = "定时器相关接口")]
    public class TimeTaskController : ApiBaseController
    {
        public ProjectDCService ProjectDCService { get; set; }

        public EfficiencyAnalyzeService EfficiencyAnalyzeService { get; set; }

        public ProjectBuildingFloorService ProjectBuildingFloorService { get; set; }

        public MsTaskDotCloudService TaskDotCloudService { get; set; }

        /// <summary>
        /// 定时器接口访问秘钥
        /// </summary>
        private readonly string apiPassport;

        public TimeTaskController(IConfiguration cfg)
        {
            apiPassport = cfg.GetValue<string>("TimeTaskPassport");
        }

        /// <summary>
        /// 推送设备的累计测量面积和测量作业时长到FMS系统
        /// </summary>
        /// <param name="passport">访问秘钥</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet, SwaggerOperation(Tags = new[] { "定时器" })]
        public async Task<ApiResult> PushDeviceStatistics([FromQuery] string passport)
        {
            if (apiPassport != passport)
                throw new OperationException("没有访问权限");

            var start_time = DateTime.Parse(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00"));
            var end_time = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
            return await PushDeviceStatistics(start_time, end_time);
        }

        /// <summary>
        /// 推送指定时间的数据
        /// </summary>
        /// <param name="passport"></param>
        /// <param name="start_time"></param>
        /// <param name="end_time"></param>
        /// <returns></returns>
        /// <exception cref="OperationException"></exception>
        [AllowAnonymous]
        [HttpGet, SwaggerOperation(Tags = new[] { "定时器" })]
        public async Task<ApiResult> PushDevicesList([FromQuery] string passport, [FromQuery] DateTime start_time, [FromQuery] DateTime end_time)
        {
            if (apiPassport != passport)
                throw new OperationException("没有访问权限");

            return await PushDeviceStatistics(start_time, end_time);
        }

        /// <summary>
        /// 推送全部数据
        /// </summary>
        /// <param name="passport">访问秘钥</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet, SwaggerOperation(Tags = new[] { "定时器" })]
        public async Task<ApiResult> PushAllDevices([FromQuery] string passport)
        {
            if (apiPassport != passport)
                throw new OperationException("没有访问权限");

            return await PushDeviceStatistics(DateTime.MinValue, DateTime.Now);
        }

        /// <summary>
        /// 推送设备
        /// </summary>
        /// <param name="start_time">开始时间</param>
        /// <param name="end_time">结束时间</param>
        /// <returns></returns>
        private async Task<ApiResult> PushDeviceStatistics(DateTime start_time, DateTime end_time)
        {
            var list = await EfficiencyAnalyzeService.GetLastDeviceStitisticsData(start_time, end_time);
            int successTotal = 0;
            int failedTotal = 0;
            foreach (var item in list)
            {
                var result = await ProjectDCService.PushDeviceStatistics(item);
                if (result == null || result.Code != 0)
                    failedTotal += 1;
                else
                    successTotal += 1;
            }

            return new ApiResult(AjaxCode.Success, $"本次推送设备数量，总共：{list.Count}，成功：{successTotal}，失败：{failedTotal}");
        }

        /// <summary>
        /// 更新FMS项目信息
        /// </summary>
        /// <param name="passport"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet, SwaggerOperation(Tags = new[] { "定时器" })]
        public async Task<ApiResult> UpdateFmsProject([FromQuery] string passport)
        {
            if (apiPassport != passport)
                throw new OperationException("没有访问权限");

            return await ProjectBuildingFloorService.UpdateFmsProject();
        }

        /// <summary>
        /// 更新数据中台项目ID映射
        /// </summary>
        /// <param name="passport"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet, SwaggerOperation(Tags = new[] { "定时器" })]
        public async Task<ApiResult> UpdateDCProjectMapId([FromQuery] string passport)
        {
            if (apiPassport != passport)
                throw new OperationException("没有访问权限");

            int count = ProjectDCService.AsyncDCProjectMapIdData();
            return new ApiResult { Code = AjaxCode.Success, Result = count };
        }

        /// <summary>
        /// 云端实测实量
        /// PS：暂时不启用该方案，使用实时方案：当接口/api/ms/DotCloud/Upload有只采模式点云上传时，即发起云端计算
        /// </summary>
        /// <param name="passport"></param>
        /// <returns></returns>
        /// <exception cref="OperationException"></exception>
        [AllowAnonymous]
        [HttpGet, SwaggerOperation(Tags = new[] { "定时器" })]
        public async Task<ApiResult> CloudMeasure([FromQuery] string passport)
        {
            if (apiPassport != passport)
                throw new OperationException("没有访问权限");

            return await TaskDotCloudService.BatchApplyCloudMeasure();
        }

        /// <summary>
        /// 云端实测报告
        /// </summary>
        /// <param name="passport"></param>
        /// <returns></returns>
        /// <exception cref="OperationException"></exception>
        [AllowAnonymous]
        [HttpGet, SwaggerOperation(Tags = new[] { "定时器" })]
        public async Task<ApiResult> CloudReport([FromQuery] string passport)
        {
            if (apiPassport != passport)
                throw new OperationException("没有访问权限");

            return await TaskDotCloudService.ApplySummaryReport();
        }
        /// <summary>
        /// 推送设备位置给FMS；
        /// 默认推送前一天的所有设备的位置记录给到FMS
        /// </summary>
        /// <param name="passport"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet, SwaggerOperation(Tags = new[] { "定时器" })]
        public async Task<ApiResult> PushDeviceLocationToFMS([FromQuery] string passport, [FromQuery] DateTime? start = null, [FromQuery] DateTime? end = null)
        {
            if (apiPassport != passport)
                throw new OperationException("没有访问权限");

            var today = DateTime.UtcNow.AddHours(8).Date;//UTC+8
            var yesterdayStart = start ?? today.AddDays(-1);
            var yesterdayEnd = end ?? today.AddTicks(-1);
            return await TryCatchAsync(ProjectDCService.PushDeviceLocation(yesterdayStart, yesterdayEnd));
            //return await TryCatchAsync(ProjectDCService.PushDeviceLocation(today, today.AddDays(1)));//测试
        }
    }
}